<template>
  <t-dialog v-model:visible="visible" attach="body" header="选择材料" width="70%">
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
      
        <!-- 类目树 -->
        <t-tree
          :data="categoryTree"
          activable
          v-model:actived="actived"
          v-model:expanded="expanded"
          expand-on-click-node
          hover
          :keys="{ label: programme.materialDataType==='3'?'projectType':'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        />
      </t-space>
      <!-- 人工 -->
      <div v-show="selectedId" class="right" v-if="programme.materialDataType==='3'">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable" >
          <t-col :span="4">
            <t-form-item label="项目类型" name="projectName">
              <t-input v-model:value="params.projectName" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="房屋户型" name="houseType">
              <t-select
                v-model:value="params.houseType"
                :options="dictionaryStore.get('decoration_order_house_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
        </custom-search>
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columnsLabor"
          :api="laborCostsCRUD.page"
          column-controller-key="laborCostsList"
          :selected-row-keys="selectedRowKeys"
          @select-change="handleSelectChange"
        >   
          <template #houseType="{ row }">
            {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
          </template>
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
        </custom-table>
      </div>
      <!-- 主材、辅材 -->
      <div v-show="selectedId" class="right" v-else>
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="4">
            <t-form-item label="材料名称" name="name">
              <t-input v-model:value="params.name" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="品牌名称" name="brandName">
              <t-input v-model:value="params.brandName" clearable placeholder="" />
            </t-form-item>
          </t-col>
        </custom-search>
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columnsType"
          :api="materialLibraryCRUD.page"
          column-controller-key="materialLibraryList"
          select
          :selected-row-keys="selectedRowKeys"
          @select-change="handleSelectChange"
        >   
          <template #fileUrl="{ row }">
            <image-viewer v-if="row.fileUrl" :images="[row.fileUrl]" width="80px" height="80px" />
          </template>  
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!selectedId" class="right" title="请先选择类目" style="margin-top: 250px" />
    </div>
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button theme="warning" @click="handleReset">重置</t-button>
      <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { laborCostsCRUD, budgetLaborCostsCRUD } from '@/api/budget/labor-costs';
import { materialLibraryNameCRUD, materialLibraryCRUD } from '@/api/budget/material-library';
import { getCompanyList } from '@/api/system/dept';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

const dictionaryStore = useDictionaryStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    required: true,
  },
  single: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['update:visible', 'save']);

const visible = ref(props.visible);
const companyId = ref();
const companySimpleList = ref([]);
const categoryList = ref([]);
const categoryTree = ref([]);
const selectedId = ref();
const actived = ref([]);
const expanded = ref([]);
const selectedRowKeys = ref([]);
const selectedRows = ref(null);
const loadingSubmit = ref(false);
const programme = ref({ materialDataType: props.type });
// columns
const columnsLabor: TableCol[] = [
  { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
  { colKey: 'projectName', title: '项目类型' },
  { colKey: 'houseType', title: '房屋类型' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'unitPrice', title: '单价(元)' },
  { colKey: 'remark', title: '备注' },
  // { colKey: 'operation', title: '操作', width: 100, fixed: 'right' },
];
// columns
const columnsType = computed<TableCol[]>(() =>[
  { colKey: 'row-select', type: props.single ? 'single' : 'multiple', width: 64, fixed: 'left' },
  { colKey: 'fileUrl', title: '封面图' },
  { colKey: 'name', title: '材料名称' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'brandName', title: '品牌名称' },
  { colKey: 'specifications', title: '规格' },
  // { colKey: 'materialDataType', title: '材料类型' },
  // { colKey: 'materialNo', title: '材料编码' },
  { colKey: 'model', title: '型号' },
  // { colKey: 'costPrice', title: '成本价(元)' },
  { colKey: 'sellingPrice', title: '售价(元)' },
  
  // { colKey: 'operation', title: '操作', fixed: 'right' },
]);
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    companyId.value = data[0].id;
  });
};

const handleGetCategory = () => {
  if (programme.value.materialDataType === '3') {
    const params = {
      companyId: companyId.value,
      pageSize: -1,
    };
    budgetLaborCostsCRUD.page(params).then((data) => {
      categoryList.value = data.list;
      categoryTree.value = listToTree(data.list);
    });
  } else {
    const params = {
      companyId: companyId.value,
      type: programme.value.materialDataType,
      pageSize: -1,
    };
    materialLibraryNameCRUD.page(params).then((data) => {
      categoryList.value = data.list;
      categoryTree.value = listToTree(data.list);
    });
  }
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');


const handleSelectChange = (keys: any[], rows: any[]) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};

const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
    companyId: companyId.value,
    laborCostsId: selectedId.value,
    materialId: selectedId.value,
    type: programme.value.materialDataType,
  };
  if (programme.value.materialDataType === '3') {
    delete params.materialId;
    delete params.type;
  } else {
    delete params.laborCostsId;
  }
  customTableRef.value.initTable(params);
};

const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (programme.value.materialDataType === '3') {
    if (!node.data.children) {
      selectedId.value = node.value;
      handleInitTable();
    }
  } else {
    if (node.data.parentId) {
      selectedId.value = node.value;
      handleInitTable();
    }
  }
};

const handleChangeCompany = () => {
  handleReset()
  handleGetCategory();
};

const handleReset = () => {
  selectedRowKeys.value = [];
  selectedRows.value = null;
  customSearchRef.value.reset(); // 重置搜索条件
  selectedId.value = null;
  actived.value = []
  expanded.value = []
  customTableRef.value.data = [];
};

const handleSelectedIds = () => {
  if (selectedRows.value.selectedRowData.length === 0) {
    MessagePlugin.warning('请先选择数据');
    return;
  }

  const selectedData = selectedRows.value.selectedRowData.map((row: any) => {
    const { id, ...rest } = row; // 解构赋值，移除 `id`
    return {
      ...rest, // 展开剩余属性
      materialId: row.id,
      materialDataType: programme.value.materialDataType,
      materialsId: row.id,
    };
  });

  selectedData.forEach((item: any) => {
    if (item.materialDataType === '3') {
      item.costPrice = item.unitPrice;
      item.sellingPrice = item.unitPrice;
    }
  });

  emits('save', selectedData);
  visible.value = false;
};

watch(
  () => props.visible,
  async (newVal) => {
    visible.value = newVal;
    if(newVal==true) {
      await handleGetCompanySimpleList();
      handleGetCategory();
      handleReset();
    }
  }
);

watch(visible, (newVal) => {
  emits('update:visible', newVal);
});

</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  .left {
    width: @leftWidth;
  }

  .right {
    width: calc(100% - @leftWidth);
  }
}
</style>